#include "TaskHandler.h"

TaskHandler::TaskHandler()
{
}

TaskHandler::~TaskHandler()
{
    stop();
}
void TaskHandler::run()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(mutex);
        if (tasks.empty())
        {
            condition.wait(lock);
        }
        else
        {
            auto task = tasks.front();
            tasks.pop();
            lock.unlock();
            task();
        }
    }
}

void TaskHandler::stop()
{
    {
        std::lock_guard<std::mutex> lock(mutex);
        tasks = std::queue<std::function<void()>>();
    }
    condition.notify_all();
}

void TaskHandler::addTask(std::function<void()> task)
{
    {
        std::lock_guard<std::mutex> lock(mutex);
        tasks.push(task);
    }
    condition.notify_one();
}


